package net.deuce.perf;

import java.io.File;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.context.ApplicationContext;

import x.y.*;
import x.y.service.*;

public class Bootstrap {
    public static void main(String[] args) {
            System.out.println("bootstrap");
        String configFile = "config.xml";
        String results = null;
        boolean manualMode = false;
        Options options = new Options();
        options.addOption("c", true, "configuration file");
        options.addOption("r", true, "generate results from previous results");
        options.addOption("m", false, "manual mode");


        CommandLineParser parser = new PosixParser();
        try {
            CommandLine cmd = parser.parse( options, args);
            if (cmd.hasOption("c")) {
                configFile = cmd.getOptionValue("c");
            }
            if (cmd.hasOption("r")) {
                results = cmd.getOptionValue("r");
                System.out.println("Using previous results: " + results);
            }
            if (cmd.hasOption("m")) {
                manualMode = true;
                System.out.println("Using manual mode.");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        File f = new File(configFile);
        if (!f.exists()) {
            System.err.println("configFile does not exist: " + configFile);
            System.exit(-1);
        }

      System.out.println("Using configuration file: " + f.getAbsolutePath());
      ApplicationContext context = new FileSystemXmlApplicationContext("file:"+f.getAbsolutePath());

        try {
            System.out.println("Executing driver");
            System.out.println("resultsDir: " + results);
            if (results == null) {
                ((Driver)context.getBean("driver", Driver.class)).execute(manualMode);
            } else {
                File resultsDir = new File(results);
                if (!resultsDir.exists()) {
                    System.err.println("resultsDir does not exist: " + results);
                    System.exit(-1);
                }
                ((Driver)context.getBean("driver", Driver.class)).execute(resultsDir);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("Test execution failed : "+ e.getMessage());
        }
    }
}
